package com.lincoln.bean;

import lombok.Data;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Api返回结构
 *
 * @author lincoln
 */
@Data
public class ApiCode {
    public static Map<Integer, ApiCode> map = new HashMap<>();
    public static final int FAIL = -1;
    public static final int SUCCESS = 1;

    static {
        try {
            Properties properties = new Properties();
            properties.load(new InputStreamReader(ApiCode.class.getClassLoader().getResourceAsStream("api_code_default.properties"), "GBK"));
            properties.load(new InputStreamReader(ApiCode.class.getClassLoader().getResourceAsStream("api_code.properties"), "GBK"));
            for (String key : properties.stringPropertyNames()) {
                if (key.endsWith(".value")) {
                    ApiCode apiCode = new ApiCode();
                    apiCode.setCode(Integer.parseInt(properties.getProperty(key)));
                    apiCode.setMsg(properties.getProperty(key.replace(".value", ".msg")));
                    map.put(apiCode.getCode(), apiCode);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static ApiCode findCode(int code) {
        ApiCode model = map.get(code);
        ApiCode apiCode = ApiCode.build();
        apiCode.setCode(model.getCode());
        apiCode.setMsg(model.getMsg());
        apiCode.setData(null);
        return apiCode;
    }

    public static ApiCode findCode(int code, Object data) {
        ApiCode model = map.get(code);
        ApiCode apiCode = ApiCode.build();
        apiCode.setCode(model.getCode());
        apiCode.setMsg(model.getMsg());
        apiCode.setData(data);
        return apiCode;
    }

    private int code;
    private String msg;
    private Object data;

    ApiCode() {
    }

    public static ApiCode build() {
        return new ApiCode();
    }

    public static ApiCode build(Object data) {
        return build(1, data);
    }

    public static ApiCode build(int code, Object data) {
        return new ApiCode(code, data);
    }

    public static ApiCode build(int code, String msg) {
        return new ApiCode(code, msg);
    }

    public static ApiCode build(int code, String msg, Object data) {
        return new ApiCode(code, msg, data);
    }

    ApiCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    ApiCode(int code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    ApiCode(int code, Object data) {
        this.code = code;
        this.data = data;
    }
}
